<?php

declare(strict_types=1);

namespace App\Helpers;

/**
 * 创蓝-一键登录
 */
class FlashLoginUtil
{
    const URL = 'https://api.253.com/open/flashsdk/mobile-query';

    //创蓝配置
    const APPKEY = [
        1 => [1 => 'ShDnep19'],
        2 => [
            101=>'PsoQCJAx',
            100 => 'Oe9UObvb',
            102 => 'eLf3WXv9'
//            101 => 'qDMwylBZ'
        ]
    ];
    const APPID = [
        1 => [1 => 'boWLjOB2'],
        2 => [
            101=> 'S1fpnHY0',
            100 => 'P4mipm5z',
            102 => 'RKuF2RuC'
//            101 => 'G5pNn7xx'
        ]
    ];
    //加密方式
    const ENCRYPT_TYPE = '0';

    /**
     * 构造参数
     */
    static function buildParams($platform = 1, $token = '', $appId = 1)
    {
        $appKey = self::APPKEY[$platform][$appId]; // 当前APP对应的appkey
        //应用私钥，可选，如用RSA解密，必须填写。
        // $privateKey = '';

        $appId = self::APPID[$platform][$appId]; // 当前APP对应的appid
        $outId = ''; // 客户流水号
        $clientIp = ''; //Helper::getClientIp2(); // 客户端IP
        $encryptType = self::ENCRYPT_TYPE; // 加密方式：0 AES 1 RSA  ， 默认0 AES

        $content = 'appId' . $appId . 'clientIp' . $clientIp . 'encryptType' . $encryptType . 'outId' . $outId . 'token' . $token;
        $sign = bin2hex(hash_hmac('sha256', $content, $appKey, true));

        return [
            'appId' => $appId,
            // 运营商token,SDK返回参数
            'token' => $token,
            'outId' => $outId,
            'clientIp' => $clientIp,
            'encryptType' => $encryptType,
            'sign' => $sign
        ];
    }

    /**
     * 登录
     */
    static function queryMobile($platform = 1, $token = '', $appId = 1)
    {
//        log_info(__CLASS__ . "aaa==" . $platform . "=={$appId}"."====".$token);
        $params = self::buildParams($platform, $token, $appId);
        $resultJson = Helper::httpReq(self::URL, $params);
        log_info(__CLASS__ . "==" . json_encode($params) . "=={$resultJson}");
        // 拿到请求结果，使用返回结果逻辑
        $requestData = json_decode($resultJson, true);
        if ($requestData['code'] == 200000) {
            $chargeStatus = $requestData['chargeStatus']; // 是否收费，枚举值：1 ：收费 0：不收费
            $mobile = $requestData['data']['mobileName']; // 手机号
            //AES解密
            $key = md5(self::APPKEY[$platform][$appId]);
            $mobile = openssl_decrypt(hex2bin($mobile), 'AES-128-CBC', substr($key, 0, 16), OPENSSL_RAW_DATA,  substr($key, 16));
            $tradeNo = $requestData['data']['tradeNo']; // 流水号
            log_info(__CLASS__ . "==Mobile:{$mobile}");
            // 拿到返回数据继续处理逻辑 TODO
            return ['mobile' => $mobile, 'errmsg' => ''];
        } else {
            return $requestData;
        }
    }
}
